package com.jk.utils;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.jk.controller.RabbitmqController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.math.BigDecimal;
import java.security.SecureRandom;
import java.util.*;

/**
* @Author: binzi
* @Description:沙箱支付工具类
* @Date: 2022/11/7 20:35
* @Return:
**/
@Component
@Controller
@RequestMapping("/")
public class AlipayUtils {

    @Autowired
    private RabbitmqController rabbitmqController;


    // 应用ID,您的APPID，收款账号既是您的APPID对应支付宝账号
    public static String APP_ID = "2021000118652308";
    // 商户私钥，您的PKCS8格式RSA2私钥
    public static String APP_PRIVATE_KEY = "MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQCWhlEBPb4nhWtvkJzUb1O++W7pJCYFMBCuCZgBRyHhPqXKqd4AkcEilzAZaDg8OP873i5dLR8rG+Lz+vl4M3txdbGyjM9zd2VsKkXsHbmlx41e4iLaAA4qU58qrDUNrDwtlirifvuQwmVg0zK3kgKU/Q0Uk7aKWMhMoBMmvPt4WY6Km1T7VjJrRK1rroIiuXk7r+AvGfz7SUzddtyBD4BJ4zOLS1ieTUGTjmRqQWkMG5s3YJ0DghPZsKjEChnbHabvWchz5j1OJulKZTS2Fi45i8sB2zqZih3DqZ2uHVSLzik8oONgWuFUhhFDztD60ZcSRCk7l9m7uPSiy8VT8d3jAgMBAAECggEAFm2bAklV3QOnN29fvtN7sffui7SEKb+4rIXnbUFRDgPMpj7bQlB1a5cFZrO9tVN0zFHVrLJ9c2nrThk2NK/PE9/Kg2Uxv+2pYg2Gb6EaOVZbfSjKsprRgYMGM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PLJPSsMfn9RrxI+meww==";
    // 支付宝公钥,查看地址：https://openhome.alipay.com/platform/keyManage.htm 对应APPID下的支付宝公钥。
    public static String ALIPAY_PUBLIC_KEY = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAqfpRj5hRBvp6uBrvDw8LO3qVCDXKzVfAn4/YPvONyzqepYsVcGQJK75aJ0Pi2yImOY3C8cW5cVV5BIs+lpHQPT3k6RpU32Ufz/w/7tmQ7af+3pRlBAlLjZVWNagOf4N9m/glyBecrCWLEqG5kARDO8h3Y8zdEjOTixC3Fyfy6ipoy5Y3+G7JoSuFSehH5E6b9wOmTTor+Z0TK9Jzq0XhfAof+9H1NNlPqNS/jj8xEjbtBI0kL0wizAp5Awu2r8S0iAykRMcqjDoCOUxi0dMUW4ILBb0xKeYq8PSxx5K7StxOqRi/XoApyupnM96Mu8BrsU5q4lABKDY2bbnfcQOTmQIDAQAB";
    //支付宝异步通知路径,付款完毕后会异步调用本项目的方法,必须为公网地址
    private final String NOTIFY_URL = "http://127.0.0.1/notifyUrl";
    //支付宝同步通知路径,也就是当付款完毕后跳转本项目的页面,可以不是公网地址
    private final String  RETURN_URL = "http://localhost:8888/returnUrl";
    // 签名方式
    public static String SIGN_TYPE = "RSA2";
    // 字符编码格式
    public static String CHARSET = "utf-8";
    // 支付宝网关
    public static String GATEWAY_URL = "https://openapi.alipaydev.com/gateway.do";
    // 支付宝网关
    public static String log_path = "C:\\";
    //格式
    private final String FORMAT = "JSON";

    private static String userId = "";


    public void alipay(String total_amount, String subject, String body, HttpServletResponse httpResponse, String out_trade_no, Integer userid) throws IOException {
        // httpResponse.setHeader("userId",String.valueOf(userid));
        userId = String.valueOf(userid);
        SecureRandom r= new SecureRandom();
        //实例化客户端,填入所需参数
        AlipayClient alipayClient = new DefaultAlipayClient(GATEWAY_URL, APP_ID, APP_PRIVATE_KEY, FORMAT, CHARSET, ALIPAY_PUBLIC_KEY, SIGN_TYPE);
        AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();
        //在公共参数中设置回跳和通知地址
        request.setReturnUrl(RETURN_URL);

        request.setNotifyUrl(NOTIFY_URL);

        //商户订单号，商户网站订单系统中唯一订单号，必填
        //生成随机Id
/*
        OrderBean orderForm = orderServiceApi.findOrderForm(userid,orderid);
*/

        request.setBizContent("{\"out_trade_no\":\""+ out_trade_no +"\","
                + "\"total_amount\":\""+ total_amount +"\","
                + "\"subject\":\""+ subject +"\","
                + "\"body\":\""+ body +"\","
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");
        String form = "";
        try {
            form = alipayClient.pageExecute(request).getBody(); // 调用SDK生成表单
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        httpResponse.setContentType("text/html;charset=" + CHARSET);
        httpResponse.getWriter().write(form);// 直接将完整的表单html输出到页面
        httpResponse.getWriter().flush();
        httpResponse.getWriter().close();
        // redisTemplate.opsForValue().set(out_trade_no,);
    }

    @RequestMapping("returnUrl")
    public String returnUrl(HttpServletRequest request, HttpServletResponse response)
            throws IOException, AlipayApiException {
        System.out.println("=================================同步回调=====================================");
        //String userId = response.getHeader("userId");
        // 获取支付宝GET过来反馈信息
        Map<String, String> params = new HashMap<String, String>();
        Map<String, String[]> requestParams = request.getParameterMap();
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
            }
            // 乱码解决，这段代码在出现乱码时使用
            valueStr = new String(valueStr.getBytes("utf-8"), "utf-8");
            params.put(name, valueStr);
        }

        System.out.println(params);//查看参数都有哪些
        boolean signVerified = AlipaySignature.rsaCheckV1(params, ALIPAY_PUBLIC_KEY, CHARSET, SIGN_TYPE); // 调用SDK验证签名
        //验证签名通过
        if(signVerified){
            // 商户订单号
            String out_trade_no = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"), "UTF-8");

            // 支付宝交易号
            String trade_no = new String(request.getParameter("trade_no").getBytes("ISO-8859-1"), "UTF-8");

            // 付款金额
            String total_amount = new String(request.getParameter("total_amount").getBytes("ISO-8859-1"), "UTF-8");

            System.out.println("商户订单号="+out_trade_no);
            System.out.println("支付宝交易号="+trade_no);
            System.out.println("付款金额="+total_amount);

            rabbitmqController.sendOne(total_amount);
            //支付成功，修复支付状态
            //orderServiceApi.updateStart(out_trade_no,userId);
            //payService.updateById(Integer.valueOf(out_trade_no));
            return "page/aliPays";//跳转付款成功页面
        }else{
            return "no";//跳转付款失败页面
        }
    }
}